package com.caijinbang.study.controller;

import com.caijinbang.study.entity.User;
import com.caijinbang.study.repository.UserRepository;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author caijb
 * @version 1.0.0
 * @date 2018-04-22 12:01
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    /**
     * 用户列表
     *
     * @return
     */
    @ApiOperation(value = "获取用户列表", notes = "获取用户列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public List<User> list() {
        return userRepository.findAll();
    }

    /**
     * 保存用户(存在id则进行更新)
     *
     * @return
     */
    @ApiOperation(value = "保存用户数据", notes = "根据User对象创建用户")
    @ApiImplicitParam(name = "user", value = "用户详细实体User", required = true, dataType = "User")
    @RequestMapping(value = "/save", method = RequestMethod.GET)
    public User save(User user) {
        return userRepository.save(user);
    }

    /**
     * 删除用户用户
     *
     * @return
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public void delete(@PathVariable("id") Long id) {
        userRepository.deleteById(id);
    }

    @RequestMapping(value = "/userName/{name}", method = RequestMethod.GET)
    @ResponseBody
    public List<User> queryUserByUserName(@PathVariable("name") String name) {
        return userRepository.queryUserByUserName(name);
    }

    /**
     * 根据用户名称和电话号码删除用户
     *
     * @param name
     * @return
     */
    @RequestMapping(value = "/delete/{name}/{phone}", method = RequestMethod.GET)
    @ResponseBody
    public void deleteByUserNameAndAndPhone(@PathVariable("name") String name, @PathVariable("phone") String phone) {
        userRepository.deleteByUserNameAndAndPhone(name, phone);
    }

    @RequestMapping(value = "/cutPage/{page}", method = RequestMethod.GET)
    public List<User> cutPage(@PathVariable("page") int page) {
        User user = new User();
        user.setSize(2);
        user.setPage(page);
        //创建分页对象
        PageRequest pageRequest = PageRequest.of(user.getPage() - 1, user.getSize(), user.getSort());
        return userRepository.findAll(pageRequest).getContent();
    }
}
